import gtk
import gtkmozembed
import os
import re
import time
import sys
import urllib2
import gobject
import mozembed_wrap
from threading import Thread

class MVFileChecker(Thread):
	CURRENT_TEMPLATE_FILE =None
	SONG_FILE='~/.quodlibet/current'
	TEMPLATES_DIR='templates'
	LAST_SONG_DATE=None
	LAST_TEMPLATE_DATE=None
	alive=True
	autoload=True
	currentTemplate=0
	
	def __init__ (self,gui):
		Thread.__init__(self)
		self.initTemplates()
		self.CURRENT_TEMPLATE_FILE=self.templateList[0]
		self.gui=gui

	def initTemplates(self):
		dir_content=os.listdir(self.TEMPLATES_DIR)
		self.templateList=[]
		for t in dir_content:
			if t[0]!= "." and t[0]!="_":
				self.templateList.append(t)
		self.templateList.sort()
		print "templates are: ", self.templateList
		

	def stop(self):
		self.alive=False
	
	def switchAutoload(self):
		if self.autoload:
			print "Autoload: off"
			self.autoload=False
		else:
			print "Autoload: on"
			self.autoload=True
	
	def switchTemplate(self):
		self.currentTemplate=((self.currentTemplate+1)%len(self.templateList))
		self.CURRENT_TEMPLATE_FILE=self.templateList[self.currentTemplate]
		self.LAST_TEMPLATE_DATE=0
		#self.gui.loadHtml()
		
	def setHomeTemplate(self):
		self.currentTemplate=0
		self.CURRENT_TEMPLATE_FILE=self.templateList[0]
		self.LAST_SONG_DATE=0
		#self.gui.loadHtml()
		

	def getAttributeByPattern(self,data,string):
		try:
			#return ""
			el= re.compile("^"+string+".*$", re.M).search(data).group()
			#el=cgi.escape(el)
			#el=urllib2.
		except:
			print "Errore: '%s' non trovato" % string
			el=""
		return el.replace(string,"")
			
	def getSongFileContent(self):
		f=open(os.path.expanduser(self.SONG_FILE), 'r')
		data = f.read()
		f.close()
		return data
	
	def getTemplatePath(self):
		return os.path.expanduser("%s/%s/index.html"%(self.TEMPLATES_DIR,self.CURRENT_TEMPLATE_FILE))
	
	def getTemplateFileContent(self):
		f=open(self.getTemplatePath(), 'r')
		data = f.read()
		f.close()
		return data

	def getCoverPath(self,data):
		clist=["cover.jpg","folder.jpg",".folder.jpg"]
		base=os.path.split(self.getAttributeByPattern(data,"~filename="))[0]
		for c in clist:
			if os.path.isfile(base+"/"+c):
				return base+"/"+c
			else:
				return os.path.abspath("./%s/%s/cover.png"%(self.TEMPLATES_DIR,self.CURRENT_TEMPLATE_FILE))
	
	def getData(self):
		try:
			data = self.getTemplateFileContent()
			song_data =self.getSongFileContent()
			
			data=data.replace("%raw_data%",song_data)
			data=data.replace("%album%",self.getAttributeByPattern(song_data,"album="))
			data=data.replace("%artist%",self.getAttributeByPattern(song_data,"artist="))
			data=data.replace("%cover%","file://"+self.getCoverPath(song_data))
			data=data.replace("%title%",self.getAttributeByPattern(song_data,"title="))
			data=data.replace("%composer%",self.getAttributeByPattern(song_data,"composer="))
			
			return data
		except:
			print "Errore nella generazione del codice HTML"
			return "<h1>ERROR: template or song file not found: probably quodlibet not started</h1>"
			
		
	def run(self):
		
		not_initialized=True
		while (not_initialized and self.alive):
			try:
				stats=os.stat(os.path.expanduser(self.getTemplatePath()))
				self.LAST_TEMPLATE_DATE=time.localtime(stats[8])
				
				stats=os.stat(os.path.expanduser(self.SONG_FILE))
				self.LAST_SONG_DATE=time.localtime(stats[8])
				
				print "Initialization completed"
				not_initialized=False
				self.gui.loadHtml()
			except:
				print "ERROR: template (%s) or song file not found: probably quodlibet not started"% self.getTemplatePath()
				#self.gui.loadHtml("<h1>ERROR: template or song file not found: probably quodlibet not started</h1>")
				time.sleep(1)
		
		
		while self.alive:
			time.sleep(1)
			if self.autoload:
				#print "Checking file change"
				try:
					template_stats=os.stat(self.getTemplatePath())
					song_stats=os.stat(os.path.expanduser(self.SONG_FILE))
					if(time.localtime(template_stats[8])>self.LAST_TEMPLATE_DATE):
						print "Template variation found"
						self.LAST_TEMPLATE_DATE=time.localtime(template_stats[8])
						self.gui.loadHtml()
					if(time.localtime(song_stats[8])>self.LAST_SONG_DATE):
						print "Song variation found"
						self.LAST_SONG_DATE=time.localtime(song_stats[8])
						time.sleep(1)
						self.gui.loadHtml()
				except:
					print "Error in update thread", sys.exc_info()[0]


class MVGui():
	
	fullscreen=False
	
	def loadHtml(self):
		data=self.fileChecker.getData()
		self.moz.set_data( "file://",data)
		
		print "Html loaded"

	def keyPressed(self,win,event):
		if event.string=="f":
			if self.fullscreen:
				self.win.unfullscreen()
				self.fullscreen=False
			else:
				self.win.fullscreen();
				self.fullscreen=True
		
		if event.string=="c":
			self.fileChecker.switchTemplate()
		if event.string=="q":
			self.quit()
		if event.string=="r":
			self.loadHtml()
		if event.string=="a":
			self.fileChecker.switchAutoload()
		if event.string=="h":
			self.fileChecker.setHomeTemplate()
					
#	def render(self, widget):
#		data=self.fileChecker.getData()
#		self.moz.render_data(data, long(len(data)), "file://", "text/html")
#		print "Html rendered"
#
#	def addIdevice(self, widget):
#		self.data += IdeviceData
#		self.render(None)
#		return True
#
#	def linkHover(self, widget):
#		print "linkHover", widget
#		return True
#
#	def linkClicked(self, widget, data):
#		print "linkClicked", widget, data
#		print self.moz.get_link_message()
	
	def __init__(self):
		gtkmozembed.set_profile_path("/tmp/","foo")
		self.fileChecker= MVFileChecker(self)
		self.fileChecker.start()
		
		self.moz = mozembed_wrap.MozClient()
		self.moz.show()
		
		#self.moz.load_url("http://www.mozilla.org/")
		self.win = gtk.Window()
		self.win.add(self.moz)
		self.win.connect("delete-event", self.quit)
		self.win.connect("key-press-event",self.keyPressed)
		self.win.set_border_width(1)
		self.win.set_title("Music Viewer")
		self.win.set_default_size(900,500)
		self.win.show_all()
		#self.win.fullscreen()
		
		
		
		#add an exit button
#		Button = gtk.Button("exit")
#		self.win.add(Button)
#		Button.connect("clicked", self.quit)
		
		self.loadHtml()
	
	def quit(self,widget=None,event=None):
		print "Procedura di chiusura"
		self.fileChecker.stop()
		gtk.main_quit()
	
	
	
	
	
if __name__ == '__main__':
	m=MVGui()
	gobject.threads_init() #rende non  bloccante il main
	gtk.main()
